<template>
  <el-dialog
    :title="loginMode"
    :visible="visible"
    :center="true"
    :modal="modal"
    :modal-append-to-body="body"
    width="400px"
    class="z-5000"
    @close="visible = false"
  >
    <el-form
      ref="formRef"
      v-loading="loginLoading"
      element-loading-spinner="el-icon-loading"
      element-loading-text="正在努力奔跑……"
      :model="form"
      :rules="formRules"
      label-width="60px"
      label-position="left"
    >
      <el-form-item
        v-if="loginMode === '注册'"
        prop="nickname"
        label="昵称"
        required
      >
        <el-input v-model="form.nickname" auto-complete="off"></el-input>
      </el-form-item>

      <el-form-item label="账号" prop="username" required>
        <el-input v-model="form.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password" required>
        <el-input
          v-model="form.password"
          type="password"
          show-password
        ></el-input>
      </el-form-item>

      <el-form-item
        v-if="loginMode === '注册'"
        prop="passwordConfirm"
        label="确认"
        required
      >
        <el-input
          v-model="form.passwordConfirm"
          type="password"
          show-password
        ></el-input>
      </el-form-item>

      <div class="submit-btns" style="display: flex; justify-content: center;">
        <el-button type="success" @click="submitLogin">登录</el-button>
        <el-button type="primary" @click="submitRegister">注册</el-button>
      </div>
    </el-form>

    <template v-slot:footer>
      <div style="color: #cccccc; font-size: 14px;">
        <div>
          本站采用企业级OAuth2认证系统
        </div>
        <div>
          请放心注册与登录~
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import qs from 'querystring'

export default {
  name: 'NcLoginDialog',
  props: {
    modal: {
      type: Boolean,
      default: true,
    },
    body: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      visible: false,
      loginLoading: false,
      loginMode: '登录',
      form: {
        nickname: '',
        username: '',
        password: '',
        passwordConfirm: '',
      },
      formRules: {
        nickname: [
          { required: true, message: '请输入你想使用的昵称', trigger: 'blur' },
        ],
        username: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('账号不能为空'))
              } else if (value.length < 4 || value.length > 16) {
                callback(new Error('账号必须在4-16位'))
              } else if (!/[0-9A-z_.\-@]+/.test(value)) {
                callback(new Error('账号只能包括数字、字母和._-@等字符'))
              } else {
                callback()
              }
            },
          },
        ],
        password: [
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('密码不能为空'))
              } else if (value.length < 8 || value.length > 16) {
                callback(new Error('密码必须在8-16位'))
              } else if (!/[0-9A-z_.\-@]+/.test(value)) {
                callback(new Error('密码只能包括数字、字母和._-@等字符'))
              } else {
                callback()
              }
            },
          },
        ],
        passwordConfirm: [
          { required: true, message: '请再次输入你的密码', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value !== this.form.password) {
                callback(new Error('两次输入密码不一致!'))
              } else {
                callback()
              }
            },
          },
        ],
      },
      loginForm: {
        username: '',
        password: '',
        scope: null, // 为空则会启用默认的scope
      },
      registerForm: {
        username: '',
        password: '',
        nickname: '',
      },
    }
  },
  methods: {
    handleOpen() {
      this.visible = true
      console.log('opened login dialog')
    },
    handleClose() {
      this.visible = false
      console.log('closed login dialog')
    },
    submitLogin() {
      const _this = this
      if (_this.loginMode !== '登录') {
        _this.loginMode = '登录'
        return
      }

      console.log('try to log in')
      _this.$refs.formRef.validate((valid) => {
        if (!valid) {
          _this.$message.error('请注意格式~')
          return
        }
        // 赋值
        _this.loginForm.username = _this.form.username
        _this.loginForm.password = _this.form.password
        _this.loginLoading = true
        _this.$http
          .post(_this.$api.apps.user.token.path, qs.stringify(_this.loginForm))
          .then((res) => {
            _this.$http.get(_this.$api.apps.user.login.path).then((res) => {
              _this.loginLoading = false
              _this.$store.commit('SET_USER', {
                hasLogined: true,
                id: res.data.id || res.data._id,
                ...res.data.detail,
              })
              _this.handleClose()
              _this.$message.success('登录成功')
            })
          })
          .catch((err) => {
            _this.loginLoading = false
            console.log({ err })
            if (err.response.status === 400) {
              _this.$message.error('用户名或密码错误，请确认！')
            } else {
              console.log('err', err)
              throw new Error(err)
            }
          })
      })
    },
    submitRegister() {
      const _this = this
      if (this.loginMode !== '注册') {
        this.loginMode = '注册'
        return
      }
      console.log('try to register')
      this.$refs.formRef.validate((valid) => {
        if (!valid) {
          this.$message.error('请注意格式~')
          return
        }
        // 赋值
        Object.assign(this.registerForm, this.form)
        this.registerForm.passwordConfirm = undefined
        this.loginLoading = true
        this.$http
          .post(this.$api.apps.user.register.path, this.registerForm)
          .then((res) => {
            this.loginLoading = false
            // console.log('res', res)
            _this.$message.success('注册成功，请登录~')
            _this.loginMode = '登录'
          })
          .catch((err) => {
            this.loginLoading = false
            console.log('err', err)
            _this.$message.error(`注册失败！原因：${err.response.data.detail}`)
            // _this.$message.error(err.detail);
          })
      })
    },
  },
}
</script>
